//
//  JrdQuestionViewController.m
//  v2ex-iOS
//
//  Created by longcheng on 16/6/15.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdQuestionViewController.h"
#import "JrdCommon.h"
#import "JrdQuestionModel.h"
#import "JrdRadioButton.h"
#import "BDRecognizerViewController.h"
#import "BDVRSConfig.h"
#import "JrdNodeModel.h"
#import "JrdQuestionModelExt.h"
#import "LCCSqliteManager.h"
#import "JrdDatamanager.h"
#import "CustomAlertView.h"
@interface JrdQuestionViewController ()<RadioButtonDelegate, BDRecognizerViewDelegate, NSXMLParserDelegate,MVoiceRecognitionClientDelegate, UIAlertViewDelegate>{
    NSInteger questionIndex;
    NSInteger radioButtonIndex;
    NSString* preString;
    int v_pinyinview_line;
    NSString* xmlElements;
    NSMutableArray* readQuestionArray;
    NSMutableArray* choiceQuestionArray;
    NSMutableArray* questionArray;

    JrdQuestionModelExt* choiceModel;
    BOOL v_is_choice;
    BOOL v_choce_item;
    UITapGestureRecognizer* tapGesture;
    int v_total_points;
    LCCSqliteManager* manager;
    Boolean isInOneSelect;
    int pre_points;
    int enters;
}
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property (nonatomic, strong) SCBarButtonItem *rightBarItem;

@property (nonatomic, strong) NSMutableArray* questionArray;
@property (nonatomic, strong) NSMutableArray* radioButtonArray;

@property (nonatomic, strong) UIView* questionView;
@property (nonatomic, strong) UILabel* titleLable;
@property (nonatomic, strong) UIView* pinyinView ;
@property (nonatomic, strong) UIView* radioView ;
@property (nonatomic, strong) UIButton *recorder_button;
@property (nonatomic, strong) UILabel* q_des;
@property (nonatomic, strong) UILabel* index_label;

@end

#define BTN_WIDTH (122)
#define BTN_HEIGHT (42)
#define BTN_VIEW_HEIGHT (60)
#define API_KEY @"QPAz9f8Y1yj3kyonnpRTq9zY"//@"8MAxI5o7VjKSZOKeBzS4XtxO" // 请修改为您在百度开发者平台申请的API_KEY
#define SECRET_KEY @"a7c925dcfbd76a7d1cf73f8184d4cbe1"//@"Ge5GXVdGQpaxOmLzc8fOM8309ATCz9Ha" // 请修改您在百度开发者平台申请的SECRET_KEY

@implementation JrdQuestionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
    self.sc_navigationItem.rightBarButtonItem = self.rightBarItem;
    questionIndex = 0;
    radioButtonIndex = 0;
    v_pinyinview_line = 0;
    pre_points=0;
    //NSString *count = [[NSUserDefaults standardUserDefaults] objectForKey:@"enter_times"];
    enters = [self.courseModel.NodeIsDownload intValue];//[count intValue];
   // [[NSUserDefaults standardUserDefaults] setObject:enters forKey:@"enter_times"];

}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [self.view setBackgroundColor:JrdBackgroundColor];
}

- (void)viewDidDisappear:(BOOL)animated{
    //[manager closeSqliteFile:@"database"];
    //[manager closeSqliteFile];
    NSLog(@"zlwu add for view disappear");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadView{
    [super loadView];
    //self.view.backgroundColor = JRD_RGB(0, 0, 200);
    [self initData]; // fake data for test
    [self configureNav];
    [self configureButton];
    readQuestionArray = [[NSMutableArray alloc] init];
    choiceQuestionArray = [[NSMutableArray alloc] init];
    questionArray =[[NSMutableArray alloc] init];
    manager = [LCCSqliteManager shareInstance];
    //[manager openSqliteFile:@"database"];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self initToParseXML];
    });
    _radioButtonArray = [[NSMutableArray alloc]init];
}

- (UIView*)getPinyinView:(CGRect) frame string:(NSString*)string index:(int)index{
    float width = 0;
    CGSize size_text=[string sizeWithFont:[UIFont systemFontOfSize:18]constrainedToSize:CGSizeMake(MAXFLOAT,Q_S_P_H)];
    NSMutableString *pinyin = [string mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CGSize size_pinyin=[pinyin sizeWithFont:[UIFont systemFontOfSize:18]constrainedToSize:CGSizeMake(MAXFLOAT,Q_S_P_H)];
    width = ((size_text.width > size_pinyin.width)?size_text.width:size_pinyin.width)+10;
    frame.size.width = width;
    UIView* PinyinView  = [[UIView alloc] initWithFrame:frame];
    
    //add 汉字
    UILabel* label1 =[[UILabel alloc] initWithFrame:CGRectMake(0, Q_S_P_H, width, Q_S_P_H)];
    label1.tag = 100+index;
    label1.font= [UIFont systemFontOfSize:18];
    label1.text = string;
    label1.textAlignment = UITextAlignmentCenter;
    
    UILabel* label2 =[[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, Q_S_P_H)];
    label2.tag = 200+index;
    label2.font = [UIFont systemFontOfSize:18];
    //add 拼音
    NSArray* pinyinArray = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",
                             @"15",@"16",@"17",@"18",@"19",@".",@",",@"?",@"，",@"。",@"？",@"(",@")",@"（",@"）"];
    if([pinyinArray containsObject:pinyin]){
        label2.text = @"";
    }else{
        label2.text = pinyin;
    }
    label2.textAlignment = UITextAlignmentCenter;
    
    [PinyinView addSubview:label2];
    [PinyinView addSubview:label1];
    return PinyinView;
}


- (void)configureQuestionView{
    float pinyinViewWidth = 0;
    float pinyinViewHeight = 0;
    NSLog(@"zlwu add for configure question view");
    if(0 ==  questionArray.count){
        return;
    }
    
    JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:questionIndex];
    _questionView = [[UIView alloc] initWithFrame:CGRectMake(0, /*STATUS_BAR_HEIGHT +*/ NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT  - BTN_VIEW_HEIGHT)];
    _questionView.backgroundColor = [UIColor clearColor];//[UIColor cleanColor];
    [self.view addSubview:_questionView];
    
    _titleLable= [[UILabel alloc] initWithFrame:CGRectMake(10, 20, SCREEN_WIDTH - 20, 40)];
    [_titleLable setFont:[UIFont systemFontOfSize:20.f]];
    [_titleLable setTextColor:[UIColor blackColor]];
    
    UIView *headerLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, 1)];
    headerLineView.backgroundColor = JrdSpeLineColor;
    [_questionView addSubview:headerLineView];
    
    //add index label
    self.index_label = [[UILabel alloc] initWithFrame:CGRectMake(15, T_Y + T_H + 20, 25, Q_S_P_H)];
    [self.index_label setText:[NSString stringWithFormat:@"%ld. ", (questionIndex +1)]];
    //[_questionView addSubview:self.index_label];

    if(QUESTION_READ == questionModel.questionType){
        //add titlelabel
        [_titleLable setText:NSLocalizedString(@"jrd_question_title_1", nil)];
        [_questionView addSubview:_titleLable];
        
        //adb pinyin view
        _pinyinView = [[UIView alloc] initWithFrame:CGRectMake(25, T_Y + T_H + 20, Q_W, Q_H)];
        //calc one line can show how much
        //int v_most_show = Q_W/Q_S_W;
        for(int i = 0; i < questionModel.questionTitle.length;i++){
            NSString *pinyinString = [questionModel.questionTitle substringWithRange:NSMakeRange(i, 1)];
            if([pinyinString containsString:@" "]){
                continue;
            }
            if((pinyinViewWidth+Q_S_W)>=(SCREEN_WIDTH - 40)){
                pinyinViewHeight += Q_S_H;
                pinyinViewWidth = 0;
            }
            UIView* pinView1 = [self getPinyinView:CGRectMake(pinyinViewWidth, pinyinViewHeight, Q_S_W, Q_S_H) string:pinyinString index:i];
            pinView1.tag = 300+i;
            pinyinViewWidth += pinView1.width;
            if(pinyinViewWidth)
            [_pinyinView addSubview:pinView1];
        }
        
        [_questionView addSubview:_pinyinView];
        
        //[self redrawRecordText:false];

        
        //add recorder icon
        //50, SCREEN_HEIGHT - BTN_HEIGHT - 70, BTN_WIDTH,BTN_HEIGHT
        _recorder_button = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 41)/2, /*T_Y + T_H + 40 + Q_H*/(SCREEN_HEIGHT - BTN_VIEW_HEIGHT - RECORD_H - (STATUS_BAR_HEIGHT + NAVIGATION_BAR_HEIGHT) -40), RECORD_W, RECORD_H)];
        [_recorder_button setBackgroundImage:[UIImage imageNamed:@"microphone"] forState:UIControlStateNormal];
        [_recorder_button addTarget:self action:@selector(beginRecoder) forControlEvents:UIControlEventTouchDown];
        [_recorder_button addTarget:self action:@selector(endRecoder) forControlEvents:UIControlEventTouchUpInside];
        [_questionView addSubview:_recorder_button];
        
        
    }else if(QUESTION_SELECT == questionModel.questionType){
        [_titleLable setText:NSLocalizedString(@"jrd_question_title_2", nil)];
        [_questionView addSubview:_titleLable];
        
        //shwo question des
        //adb pinyin view
        _pinyinView = [[UIView alloc] initWithFrame:CGRectMake(35, T_Y + T_H + 20, Q_W, Q_H)];
        //calc one line can show how much
        int v_most_show = Q_W/Q_S_W;
        if (questionModel.questionTitle.length >v_most_show) {
            for(int i = 0; i < questionModel.questionTitle.length; i ++){
                if(i < 8){
                    NSString *pinyinString = [questionModel.questionTitle substringWithRange:NSMakeRange(i, 1)];
                    UIView* pinView1 = [self getPinyinView:CGRectMake(i*Q_S_W, 0, Q_S_W, Q_S_H) string:pinyinString index:i];
                    [_pinyinView addSubview:pinView1];
                }else{
                    NSString *pinyinString = [questionModel.questionTitle substringWithRange:NSMakeRange(i, 1)];
                    UIView* pinView1 = [self getPinyinView:CGRectMake(i*Q_S_W, Q_S_H, Q_S_W, Q_S_H) string:pinyinString index:i];
                    [_pinyinView addSubview:pinView1];
                }
            }
        }else{
            //计算七点左边
            int start_x = 0;//(Q_W - questionModel.questionDes.length * Q_S_W)/2;
            for(int i = 0; i < questionModel.questionTitle.length; i ++){
                NSString *pinyinString = [questionModel.questionTitle substringWithRange:NSMakeRange(i, 1)];
                UIView* pinView1 = [self getPinyinView:CGRectMake(i*Q_S_W + start_x, 0, Q_S_W, Q_S_H) string:pinyinString index:i];
                [_pinyinView addSubview:pinView1];
            }
            
        }
        [_questionView addSubview:_pinyinView];

        
        //show radio button group
        int radioView_y = (SCREEN_HEIGHT - BTN_VIEW_HEIGHT) - 4*50;
        _radioView = [[UIView alloc] initWithFrame:CGRectMake(20, /*_q_des.origin.y + Q_H +10*/radioView_y, Q_W, R_H)];
        //[_radioView setBackgroundColor:[UIColor grayColor]];
        //show choice select
        //Choice A
        if(![questionModel.questionChoice1 isEqualToString:@""]){
            JrdRadioButton* radioButton = [[JrdRadioButton alloc] initWithGroupId:@"anwser" index:0];
            radioButton.frame= CGRectMake(10, 30, R_B_W, R_B_h);
            UILabel* answer_des = [[UILabel alloc] initWithFrame:CGRectMake(40, 30, Q_W - 40, 20)];
            answer_des.text = questionModel.questionChoice1;
            [_radioView addSubview:radioButton];
            [_radioView addSubview:answer_des];
        }

        //Choice B
        if(![questionModel.questionChoice2 isEqualToString:@""]){
            JrdRadioButton* radioButton = [[JrdRadioButton alloc] initWithGroupId:@"anwser" index:0];
            radioButton.frame= CGRectMake(10, 30*1, R_B_W, R_B_h);
            UILabel* answer_des = [[UILabel alloc] initWithFrame:CGRectMake(40, 30*1, Q_W - 40, 20)];
            answer_des.text = questionModel.questionChoice2;//[questionModel.questionChoice1 objectAtIndex:i];
            [_radioView addSubview:radioButton];
            [_radioView addSubview:answer_des];
        }

        //Choice C
        if(![questionModel.questionChoice3 isEqualToString:@""]){
            JrdRadioButton* radioButton = [[JrdRadioButton alloc] initWithGroupId:@"anwser" index:0];
            radioButton.frame= CGRectMake(10, 30*2, R_B_W, R_B_h);
            UILabel* answer_des = [[UILabel alloc] initWithFrame:CGRectMake(40, 30*2, Q_W - 40, 20)];
            answer_des.text = questionModel.questionChoice3;//[questionModel.questionChoice1 objectAtIndex:i];
            [_radioView addSubview:radioButton];
            [_radioView addSubview:answer_des];
        }

        //Choice D
        if(![questionModel.questionChoice4 isEqualToString:@""]){
            JrdRadioButton* radioButton = [[JrdRadioButton alloc] initWithGroupId:@"anwser" index:0];
            radioButton.frame= CGRectMake(10, 30*2, R_B_W, R_B_h);
            UILabel* answer_des = [[UILabel alloc] initWithFrame:CGRectMake(40, 30*2, Q_W - 40, 20)];
            answer_des.text = questionModel.questionChoice4;//[questionModel.questionChoice1 objectAtIndex:i];
            [_radioView addSubview:radioButton];
            [_radioView addSubview:answer_des];
        }
        
        
    }
    
    for(int i = 0; i < questionArray.count; i++){
        JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
        v_total_points += questionModel.questionValue;
    }
}

- (void)updateQuestionView{
    JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:questionIndex];
    int v_show_line = 0;
    int v_height = 0;
    if(nil == _pinyinView){
        _pinyinView = [[UIView alloc] initWithFrame:CGRectMake(20, T_Y + T_H + 20, Q_W, Q_H)];
        [_questionView addSubview:_pinyinView];
    }else{
        for(UIView* subview in [_pinyinView subviews]){
            [subview removeFromSuperview];
        }
    }
    
    //update next button
    if(questionIndex == (questionArray.count - 1)){
        [self.next_button setTitle:NSLocalizedString(@"Jrd_sumbit", nil) forState:UIControlStateNormal];
        
    }else{
        [self.next_button setTitle:NSLocalizedString(@"Jrd_next", nil) forState:UIControlStateNormal];
    }
    //calc one line can show how much
    //int v_most_show = Q_W/Q_S_W;
    float pinyinViewWidth = 0;
    float pinyinViewHeight = 0;
    for(int i = 0; i < questionModel.questionTitle.length;i++){
        NSString *pinyinString = [questionModel.questionTitle substringWithRange:NSMakeRange(i, 1)];
        if((pinyinViewWidth+Q_S_W)>=(SCREEN_WIDTH - 40)){
            pinyinViewHeight += Q_S_H;
            pinyinViewWidth = 0;
        }
        UIView* pinView1 = [self getPinyinView:CGRectMake(pinyinViewWidth, pinyinViewHeight, Q_S_W, Q_S_H) string:pinyinString index:i];
        pinView1.tag = 300+i;
        pinyinViewWidth += pinView1.width;
        if(pinyinViewWidth)
            [_pinyinView addSubview:pinView1];
    }
    


    if(QUESTION_READ == questionModel.questionType){
        //[self redrawRecordText:false];

        [_titleLable setText:NSLocalizedString(@"jrd_question_title_1", nil)];
        [_radioView removeFromSuperview];
        _radioView = nil;
        
        //adb pinyin view
        if(nil == _recorder_button){
            _recorder_button = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 41)/2, (SCREEN_HEIGHT - BTN_VIEW_HEIGHT - RECORD_H -(STATUS_BAR_HEIGHT + NAVIGATION_BAR_HEIGHT)- 40), RECORD_W, RECORD_H)];
            [_recorder_button setBackgroundImage:[UIImage imageNamed:@"microphone"] forState:UIControlStateNormal];
            [_recorder_button addTarget:self action:@selector(beginRecoder) forControlEvents:UIControlEventTouchDown];
            [_recorder_button addTarget:self action:@selector(endRecoder) forControlEvents:UIControlEventTouchUpInside];
            [_questionView addSubview:_recorder_button];
        }
        
    }else if(QUESTION_SELECT == questionModel.questionType){
        [_titleLable setText:NSLocalizedString(@"jrd_question_title_2", nil)];
        [_recorder_button removeFromSuperview];
        _recorder_button = nil;

        if(_q_des == nil){
            _q_des = [[UILabel alloc] initWithFrame:CGRectMake(20, T_Y + T_H + 20, Q_W, Q_H/4)];
            [_q_des setFont:[UIFont systemFontOfSize:18]];
        }
        _q_des.text = questionModel.questionTitle;
        //isInOneSelect = true;
        //pre_points = (int)questionModel.questionValue;
        if(nil == _radioView){
            if(1 == v_show_line){
                v_height = Q_H/2;
            }else{
                v_height = Q_H;
            }
            int radioView_y = (SCREEN_HEIGHT - BTN_VIEW_HEIGHT - NAVIGATION_BAR_HEIGHT) - 4*50;

            _radioView = [[UIView alloc] initWithFrame:CGRectMake(20, /*T_Y + T_H + 20+v_height*/radioView_y , Q_W, R_H)];
            [_questionView addSubview:_radioView];
        }
        [_radioButtonArray removeAllObjects];
        [self updateChoiceTitle:questionModel.questionChoice1 index:0];
        [self updateChoiceTitle:questionModel.questionChoice2 index:1];
        [self updateChoiceTitle:questionModel.questionChoice3 index:2];
        [self updateChoiceTitle:questionModel.questionChoice4 index:3];

        //按照GroupId添加观察者
        [JrdRadioButton addObserverForGroupId:@"anwser" observer:self];
    }
}

- (void)updateChoiceTitle: (NSString*)title index:(int)i{
    JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:questionIndex];

    JrdRadioButton* radioButton = [[JrdRadioButton alloc] initWithGroupId:@"anwser" index:i];
    if([title isEqualToString:@""]){
        return;
    }
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 50*i,(SCREEN_WIDTH - 40),  40)];
    UIColor* color = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_normal"] andResizeTo:view.frame.size]];
    view.tag = i;
    [_radioButtonArray addObject:view];
    tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickRadio:)];
    
    [view addGestureRecognizer:tapGesture];
    //get correct one
    if(questionModel.questionUserAnswer.length != 0){
        UIColor* correct_color = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_correct"] andResizeTo:view.frame.size]];
        UIColor* wrong_color = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_wrong"] andResizeTo:view.frame.size]];
        UIColor* normal_color = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_rd_nornmal"] andResizeTo:view.frame.size]];

        NSString* current_String;
        //check this one is correct
        switch (i) {
            case 0:
                current_String = questionModel.questionChoice1;
                break;
            case 1:
                current_String = questionModel.questionChoice2;
                break;
            case 2:
                current_String = questionModel.questionChoice3;
                break;
            case 3:
                current_String = questionModel.questionChoice4;
                break;

            default:
                break;
        }
        int answer_index = 4;
        if([questionModel.questionAnswer containsString:@"a"]){
            answer_index = 0;
        }else if([questionModel.questionAnswer containsString:@"b"]){
            answer_index = 1;

        }else if([questionModel.questionAnswer containsString:@"c"]){
            answer_index = 2;

        }else if([questionModel.questionAnswer containsString:@"d"]){
            answer_index = 3;

        }
        
        if([current_String isEqualToString:questionModel.questionUserAnswer] && JrdQuestionCount <= enters){
            if([current_String isEqualToString:questionModel.questionAnswer] ||(i == answer_index)){
                [view setBackgroundColor:color/*correct_color*/];
            }else{
                [view setBackgroundColor:color/*wrong_color*/];
            }
        }else{
            [view setBackgroundColor:color];

        }
        /*if([current_String isEqualToString:questionModel.questionAnswer]||(i == answer_index)){
            [view setBackgroundColor:correct_color];
        }else{
            if([current_String isEqualToString:questionModel.questionUserAnswer]){
                [view setBackgroundColor:wrong_color];
            }else{
                [view setBackgroundColor:color];
            }
        }*/
    }else{
        [view setBackgroundColor:color];
    }
    [_radioView addSubview:view];
    radioButton.frame= CGRectMake(10, (50 -R_B_h)/2, R_B_W, R_B_h);
    UILabel* answer_des = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, Q_W - 40, 40)];
    answer_des.text = title;//[questionModel.answerArray objectAtIndex:i];
    //[view addSubview:radioButton];
    [view addSubview:answer_des];
    if(i == radioButtonIndex){
        [radioButton ButtonSelected];
    }

}

- (void)clickRadio:(id)sender{
    Boolean v_show_con = false;
    JrdQuestionModelExt* jrdModel = [questionArray objectAtIndex:questionIndex];
    int local_point = 0;
    if(jrdModel.questionUserAnswer.length != 0){
        //Has answer this question, just return
        //return;
    }
    if(questionIndex == (questionArray.count - 1) && jrdModel.questionUserAnswer.length ==0){
        v_show_con = true;
    }
    //check the correct andswer
    int correct_index = 0;
    if([jrdModel.questionAnswer isEqualToString:jrdModel.questionChoice1] || [jrdModel.questionAnswer containsString:@"a"]){
        correct_index = 0;
    }else if([jrdModel.questionAnswer isEqualToString:jrdModel.questionChoice2]||[jrdModel.questionAnswer containsString:@"b"]){
        correct_index =1;
    }else if([jrdModel.questionAnswer isEqualToString:jrdModel.questionChoice3]||[jrdModel.questionAnswer containsString:@"c"]){
        correct_index = 2;
    }else if([jrdModel.questionAnswer isEqualToString:jrdModel.questionChoice4]||[jrdModel.questionAnswer containsString:@"d"]){
        correct_index = 3;
    }
    

    UIGestureRecognizer *ges = (UIGestureRecognizer*)sender;
    UIView *view = ges.view;
    UIColor* correct_color = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_correct"] andResizeTo:view.frame.size]];
    UIColor* wrong_color = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_wrong"] andResizeTo:view.frame.size]];
    UIColor* normal_color = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_normal"] andResizeTo:view.frame.size]];
    UIColor* normal_color_ext = [UIColor colorWithPatternImage:[self imageResize:[UIImage imageNamed:@"item_rd_nornmal"] andResizeTo:view.frame.size]];

    for(UIView* view  in _radioButtonArray){
        //if(radioButtonIndex == view.tag){
            [view setBackgroundColor:normal_color];
        //}
    }
    if(ges.view.tag == correct_index){
        //v_total_points +=jrdModel.questionValue;
        local_point = 5;
        jrdModel.questionValue = 5;
        [self updateRightItem];
        if(JrdQuestionCount<=enters)
        [view setBackgroundColor:correct_color];
        else{
            [view setBackgroundColor:normal_color_ext];

        }
        //pre_points =5;
    }else{
        local_point = 0;
        if(JrdQuestionCount<=enters)

        [view setBackgroundColor:wrong_color];
        else{
            [view setBackgroundColor:normal_color_ext];

        }
        jrdModel.questionValue = 0;
        //[self updateRightItem];
    }
    
    
    radioButtonIndex = ges.view.tag;
    
    //fill the info into model
    switch (ges.view.tag) {
        case 0:
            jrdModel.questionUserAnswer = jrdModel.questionChoice1;
            break;
        case 1:
            jrdModel.questionUserAnswer = jrdModel.questionChoice2;
            break;
        case 2:
            jrdModel.questionUserAnswer = jrdModel.questionChoice3;
            break;
        case 3:
            jrdModel.questionUserAnswer = jrdModel.questionChoice4;
            break;
        default:
            break;
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if(0 == buttonIndex){
        [self.navigationController popViewControllerAnimated:YES];
        [self backToPrevious];
    }
}

-(UIImage *)imageResize :(UIImage*)img andResizeTo:(CGSize)newSize
{
    CGFloat scale = [[UIScreen mainScreen]scale];
    
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
    [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)initData{
    self.questionArray = [[NSMutableArray alloc] init];
    JrdQuestionModel* model1 = [[JrdQuestionModel alloc] init];
    model1.questionId = 1;
    model1.questionType = QUESTION_READ;
    model1.questionDes = @"你叫什么名字";
    [self.questionArray addObject:model1];
    JrdQuestionModel* model2 = [[JrdQuestionModel alloc] init];
    model2.questionId = 2;
    model2.questionType = QUESTION_READ;
    model2.questionDes = @"你来自哪里，你想要说什么";
    [self.questionArray addObject:model2];
    
    JrdQuestionModel* model3 =[[JrdQuestionModel alloc] init];
    model3.questionId = 3;
    model3.questionType = QUESTION_SELECT;
    model3.questionDes = @"你多大年纪？";
    model3.answerArray = [[NSMutableArray alloc] init];
    NSString* answer1 = @"A. yidian/一点";
    [model3.answerArray addObject:answer1];
    NSString* answer2 = @"B. youdian/有点";
    [model3.answerArray addObject:answer2];
    NSString* answer3 = @"C. youyidian/有一点";
    [model3.answerArray addObject:answer3];
    [self.questionArray addObject:model3];
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    CGFloat imageW = 1 ;
    CGFloat imageH = 1;
    // 1.开启基于位图的图形上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageW, imageH), NO, 0.0);
    // 2.画一个color颜色的矩形框
    [color set];
    UIRectFill(CGRectMake(0, 0, imageW, imageH));
    
    // 3.拿到图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 4.关闭上下文
    UIGraphicsEndImageContext();
    
    return image;
}
- (void)configureButton{
    UIView* btnView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - BTN_VIEW_HEIGHT, SCREEN_WIDTH, BTN_VIEW_HEIGHT)];
    [btnView setBackgroundColor:JrdTableHeadColor];
    [self.view addSubview:btnView];
    
    UIButton* pre_button = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH/2 -BTN_WIDTH)/2, (BTN_VIEW_HEIGHT - BTN_HEIGHT)/2, BTN_WIDTH, BTN_HEIGHT)];
    [pre_button setBackgroundImage:[UIImage imageNamed:@"btn_next_normal"] forState:UIControlStateNormal];
    [pre_button setBackgroundImage:[UIImage imageNamed:@"btn_next_press"] forState:UIControlStateHighlighted];

    [pre_button setTitle:NSLocalizedString(@"Jrd_previous", nil) forState:UIControlStateNormal];
    [pre_button setTitleColor:JRD_RGB(104, 211, 132) forState:UIControlStateNormal];
    [pre_button setTitleColor:JrdWhite1Color   forState:UIControlStateHighlighted];
    [pre_button addTarget:self action:@selector(gotoPreQuestion) forControlEvents:UIControlEventTouchUpInside];

    [btnView addSubview:pre_button];
    self.next_button = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH/2 -BTN_WIDTH)/2 + (SCREEN_WIDTH)/2, (BTN_VIEW_HEIGHT - BTN_HEIGHT)/2, BTN_WIDTH, BTN_HEIGHT)];
    [self.next_button setBackgroundImage:[UIImage imageNamed:@"btn_next_normal"] forState:UIControlStateNormal];

    [self.next_button setBackgroundImage:[UIImage imageNamed:@"btn_next_press"] forState:UIControlStateHighlighted];
    [self.next_button setTitle:NSLocalizedString(@"Jrd_next", nil) forState:UIControlStateNormal];
    [self.next_button setTitleColor:JRD_RGB(104, 211, 132)  forState:UIControlStateNormal];
    [self.next_button setTitleColor:JrdWhite1Color   forState:UIControlStateHighlighted];
    [btnView addSubview:self.next_button];
    [self.next_button addTarget:self action:@selector(gotoNextQuestion) forControlEvents:UIControlEventTouchUpInside];


};

//UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_congra", nil) message:conString delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];

- (void)showPopupView{
    /*title:(NSString*)title info:(NSString*)popInfo image:(UIImage*)image  buttonString:(NSString*)buttonString
    CustomAlertView *alert = [[CustomAlertView alloc] ]//[[CustomAlertView alloc] initWithAlertViewHeight:206 title:];
    
    alert.ButtonClick = ^void(UIButton*button){
        NSLog(@"%ld",(long)button.tag);
        
        if (button.tag==100) {
            //look  rili
            
        }
    };*/

    NSString* alertTitle;
    NSString* alertImage;
    int total_points = 0;
    for(int i = 0; i< questionArray.count;i ++){
        JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
        total_points+=questionModel.questionValue;
    }
    NSString* conString= [NSString stringWithFormat:NSLocalizedString(@"jrd_get_score", nil),total_points];

    if(0<=total_points && 59>= total_points){
        alertTitle = NSLocalizedString(@"jrd_terrible", nil);
        alertImage = @"Terrible.jpg";
    }else if(60<=total_points && total_points<= 84){
        alertTitle = NSLocalizedString(@"jrd_good", nil);
        alertImage = @"Good.jpg";
    }else if(85<=total_points && total_points <=100){
        alertTitle = NSLocalizedString(@"jrd_awesome", nil);
        alertImage = @"Awesome.jpg";
    }

    CustomAlertView* alert = [[CustomAlertView alloc] initWithAlertViewHeight:204 title:alertTitle info:conString image:[UIImage imageNamed:alertImage] leftButton:NSLocalizedString(@"Jrd_upload", nil) rightButton:NSLocalizedString(@"jrd_done", nil)];
    alert.ButtonClick = ^void(UIButton*button){
        switch (button.tag) {
            case 101:
                [self launchMailApp];
                break;
            case 102:
                [self.navigationController popViewControllerAnimated:YES];
                [self backToPrevious];
                break;
            default:
                break;
        }
    };
}

-(void)launchMailApp
{
    NSMutableString *mailUrl = [[NSMutableString alloc]init];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"first@example.com"];
    [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]];
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
    [mailUrl appendFormat:@"?cc=%@", [ccRecipients componentsJoinedByString:@","]];
    //添加密送
    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
    [mailUrl appendFormat:@"&bcc=%@", [bccRecipients componentsJoinedByString:@","]];
    //添加主题
    [mailUrl appendString:@"&subject=my email"];
    //添加邮件内容
    [mailUrl appendString:@"&body=<b>email</b> body!"];
    NSString* email = [mailUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
    [self backToPrevious];
}
- (void)gotoPreQuestion{
    NSLog(@"zlwu add go to pre question");
    if(questionIndex <= 0){
        
    }else{
        questionIndex--;
        [self updateQuestionView];
    }
    [self.index_label setText:[NSString stringWithFormat:@"%ld. ", (questionIndex +1)]];
    [self updateRightItem];
}

- (void)gotoNextQuestion{
    NSLog(@"zlwu add to goto next question");
    if(questionIndex >= (questionArray.count - 1) || (0 == questionArray.count)){
        //最后一题
        /*NSString* conString= [NSString stringWithFormat:NSLocalizedString(@"jrd_get_score", nil),v_total_points];
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_congra", nil) message:conString delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
        UIImageView *viewe = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 45.0, 45.0)];
        
        viewe.image = [UIImage imageNamed:@"switch_off.png"];
        
        [alertView addSubview:viewe];
        [alertView show];*/
        [self showPopupView];
    }else{
        questionIndex++;
        [self updateQuestionView];
    }
    [self.index_label setText:[NSString stringWithFormat:@"%ld. ", (questionIndex +1)]];

    [self updateRightItem];
}

- (void)backToPrevious{
    //int count = [enters intValue];
    for(int i = 0; i < questionArray.count; i++){
        JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
        if(questionModel.questionUserAnswer == nil){
            questionModel.questionUserAnswer = @"";
        }
    }
    
    if(0 != questionArray.count){
        NSString * searchCondition = [NSString stringWithFormat:@"question_node_id=%@ and user_id=%@",
                                      _courseModel.NodeID,[JrdDatamanager manager].user.userId];
        
        NSArray* nodeListData= [manager searchDataFromSheet:@"question_list" where:searchCondition];
        if(0 == nodeListData.count){
            for(int i = 0; i < questionArray.count; i++){
                JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
                NSString* answer = questionModel.questionUserAnswer;
                //int value = questionModel.questionValue;
                if(enters<JrdQuestionCount){
                    answer = @"";
                    //value = 0;//@"";
                }
                Boolean ret = [manager insertDataToSheetWithAutoQuestion_ext:@"question_list" withData:@[
                                                                                                         [JrdDatamanager manager].user.userId,
                                                                                                         _courseModel.NodeID,
                                                                                                         questionModel.questionUserAnswer,
                                                                                                         [NSString stringWithFormat:@"%ld",(long)questionModel.questionValue],
                                                                                                         ]];
                NSLog(@"ret = %d", ret);
            }
        }else{
            for(int i = 0; i < questionArray.count; i++){
                JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
                NSString * searchConditionE = [NSString stringWithFormat:@"question_node_id=%@ and question_id=%d and user_id=%@",
                                               _courseModel.NodeID,(i+1),[JrdDatamanager manager].user.userId];
                
                Boolean ret = [manager updateDataToSheet_questionExt:@"question_list" withData:@[
                                                                                                 questionModel.questionUserAnswer,
                                                                                                 [NSString stringWithFormat:@"%ld",(long)questionModel.questionValue],
                                                                                                 ]
                                                               where:searchConditionE
                               ];
                NSLog(@"ret = %d", ret);
            }
            
        }
        
        
    }
    //update enters
    if(enters<JrdQuestionCount){
        enters++;
    }
    
    NSString * searchCondition = [NSString stringWithFormat:@"node_id='%@' and node_parentid= '%@' and user_id=%@",self.courseModel.NodeID,self.courseModel.NodeParentID,[JrdDatamanager manager].user.userId];
    
    //[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",enters] forKey:@"enter_times"];
    Boolean ret = [manager updateDataToSheet_CourseDetail_Ext:@"nodelist" withData:@[[NSString stringWithFormat:@"%d",enters]]                                                  where:searchCondition];
    NSLog(@"zlwu","ret = %d",ret);
    [[NSNotificationCenter defaultCenter] postNotificationName:kReloadDataNotification object:self];

}

- (void)configureNav{
    NSString* rightItem = [NSString stringWithFormat:@"%d %@    %ld/%lu",v_total_points,NSLocalizedString(@"jrd_point", nil),(long)(questionIndex + 1), (unsigned long)questionArray.count];

    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_back"] highlight:[UIImage imageNamed:@"btn-back-normal"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        //save the 
        [self.navigationController popViewControllerAnimated:YES];
        [self backToPrevious];
        /*for(int i = 0; i < questionArray.count; i++){
            JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
            if(questionModel.questionUserAnswer == nil){
                questionModel.questionUserAnswer = @"";
            }
        }
        if(0 != questionArray.count){
            NSString * searchCondition = [NSString stringWithFormat:@"question_node_id=%@ and user_id=%@",
                                          _courseModel.NodeID,[JrdDatamanager manager].user.userId];
            
            NSArray* nodeListData= [manager searchDataFromSheet:@"question_list" where:searchCondition];
            if(0 == nodeListData.count){
                for(int i = 0; i < questionArray.count; i++){
                    JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];

                    Boolean ret = [manager insertDataToSheetWithAutoQuestion_ext:@"question_list" withData:@[
                            [JrdDatamanager manager].user.userId,
                             _courseModel.NodeID,
                            questionModel.questionUserAnswer,
                            [NSString stringWithFormat:@"%ld",(long)questionModel.questionValue],
                        ]];
                     NSLog(@"ret = %d", ret);
                }
            }else{
                for(int i = 0; i < questionArray.count; i++){
                    JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
                    NSString * searchConditionE = [NSString stringWithFormat:@"question_node_id=%@ and question_id=%d and user_id=%@",
                                                  _courseModel.NodeID,(i+1),[JrdDatamanager manager].user.userId];

                    Boolean ret = [manager updateDataToSheet_questionExt:@"question_list" withData:@[
                                    questionModel.questionUserAnswer,
                                    [NSString stringWithFormat:@"%ld",(long)questionModel.questionValue],
                                   ]
                                   where:searchConditionE
                                   ];
                    NSLog(@"ret = %d", ret);
                }

            }
        }*/
    }];
    self.rightBarItem  = [[SCBarButtonItem alloc] initWithTitle:rightItem style:SCBarButtonItemStylePlain handler:^(id sender){
        
    }];
    self.sc_navigationItem.title = _courseModel.NodeName;//NSLocalizedString(@"jrd_test",nil);//@"我们学习";
}

- (void)updateRightItem{
    int total_points = 0;
    for(int i = 0; i< questionArray.count;i ++){
        JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
        total_points+=questionModel.questionValue;
    }
    NSString* rightItem = [NSString stringWithFormat:@"%d %@    %ld/%lu",total_points,NSLocalizedString(@"jrd_point", nil),(long)(questionIndex + 1), (unsigned long)questionArray.count];

    [self.rightBarItem updateTitle:rightItem];
}
- (void)updateRightItem:(int)points{
    int total_points = 0;
    for(int i = 0; i< questionArray.count;i ++){
        JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
        
        total_points+=questionModel.questionValue;
    }
    NSString* rightItem = [NSString stringWithFormat:@"%d %@    %ld/%lu",v_total_points+points,NSLocalizedString(@"jrd_point", nil),(long)(questionIndex + 1), (unsigned long)questionArray.count];
    
    [self.rightBarItem updateTitle:rightItem];
}

-(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString *)groupId{
    radioButtonIndex = index;
}

#pragma mark - show View

- (void)beginRecoder{
    NSLog(@"zlwu use baidu to begin recoder");
    // 创建识别控件
    BDRecognizerViewController *tmpRecognizerViewController = [[BDRecognizerViewController alloc] initWithOrigin:CGPointMake((SCREEN_WIDTH - 300)/2, /*(SCREEN_HEIGHT-230)/2)*/SCREEN_HEIGHT - BTN_VIEW_HEIGHT - 230-10)  withTheme:[BDVRSConfig sharedInstance].theme];
    [tmpRecognizerViewController.view setAlpha:0.5];
   // [tmpRecognizerViewController.view setSize:CGSizeMake(200, 100)];
    // 全屏UI
    if ([[BDVRSConfig sharedInstance].theme.name isEqualToString:@"全屏亮蓝"]) {
        tmpRecognizerViewController.enableFullScreenMode = YES;
    }
    
    tmpRecognizerViewController.delegate = self;
    self.recognizerViewController = tmpRecognizerViewController;
    
    // 设置识别参数
    BDRecognizerViewParamsObject *paramsObject = [[BDRecognizerViewParamsObject alloc] init];
    
    // 开发者信息，必须修改API_KEY和SECRET_KEY为在百度开发者平台申请得到的值，否则示例不能工作
    paramsObject.apiKey = API_KEY;
    paramsObject.secretKey = SECRET_KEY;
    
    // 设置是否需要语义理解，只在搜索模式有效
    paramsObject.isNeedNLU = [BDVRSConfig sharedInstance].isNeedNLU;
    
    // 设置识别语言
    paramsObject.language = [BDVRSConfig sharedInstance].recognitionLanguage;
    
    // 设置识别模式，分为搜索和输入
    paramsObject.recogPropList = @[[BDVRSConfig sharedInstance].recognitionProperty];
    
    // 设置城市ID，当识别属性包含EVoiceRecognitionPropertyMap时有效
    paramsObject.cityID = 1;
    
    // 开启联系人识别
    //    paramsObject.enableContacts = YES;
    
    // 设置显示效果，是否开启连续上屏
    if ([BDVRSConfig sharedInstance].resultContinuousShow)
    {
        paramsObject.resultShowMode = BDRecognizerResultShowModeContinuousShow;
    }
    else
    {
        paramsObject.resultShowMode = BDRecognizerResultShowModeWholeShow;
    }
    
    // 设置提示音开关，是否打开，默认打开
    if ([BDVRSConfig sharedInstance].uiHintMusicSwitch)
    {
        paramsObject.recordPlayTones = EBDRecognizerPlayTonesRecordPlay;
    }
    else
    {
        paramsObject.recordPlayTones = EBDRecognizerPlayTonesRecordForbidden;
    }
    
    //Test uncertain:
    [[BDVoiceRecognitionClient sharedInstance] setProductId:@"790"];
    paramsObject.isNeedOriginJsonResult = YES;
    
    paramsObject.isShowTipAfterSilence = NO;
    paramsObject.isShowHelpButtonWhenSilence = NO;
    paramsObject.tipsTitle = @"可以使用如下指令记账";
    paramsObject.tipsList = [NSArray arrayWithObjects:@"我要记账", @"买苹果花了十块钱", @"买牛奶五块钱", @"第四行滚动后可见", @"第五行是最后一行", nil];
    
    [_recognizerViewController startWithParams:paramsObject];
}

- (void)endRecoder{
    NSLog(@"zlwu use baidu to stop recoder");

}

- (void)beginRecoderExt{
    BDVoiceRecognitionClient*sharedInstance=[BDVoiceRecognitionClient sharedInstance];
     //[[BDVoiceRecognitionClient sharedInstance] setLanguage: EVoiceRecognitionLanguageEn
     //glish];
    [sharedInstance setLanguage:EVoiceRecognitionLanguageChinese];
    //[sharedInstance setApiKey:@"apiKey " withSecretKey:@”se
    //cretKey”];
    [sharedInstance setApiKey:API_KEY withSecretKey:SECRET_KEY];
    
    int startStatus = [sharedInstance startVoiceRecognition:self];
    switch (startStatus) {
        case EVoiceRecognitionStartWorking:
            
            break;
            
        default:
            break;
    }
    
}


- (void)onEndWithViews:(BDRecognizerViewController *)aBDRecognizerView withResults:(NSArray *)aResults
{
    JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:questionIndex];
    questionModel.questionUserAnswer = aResults[0];
    [self redrawRecordText: true];
    
}
- (NSString*)filterString:(NSString*)string{
    
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"1234567890.。,“’，？? "];
    NSString* result_string = [string stringByTrimmingCharactersInSet:set];
    return result_string;
}

- (void)redrawRecordText: (Boolean)addPoint{
    int v_correct_count = 0;
    int j = 0;
    JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:questionIndex];
    if(nil == questionModel.questionUserAnswer || 0 == questionModel.questionUserAnswer.length){
        return;
    }
    //questionModel.questionUserAnswer = @"你每个心期去几次健身房";
    //NSInteger index = [questionModel.questionTitle rangeOfString:@"."].location;
    //NSString* questionStr = [self filterString:questionModel.questionTitle];//[questionModel.questionTitle substringFromIndex:(index +1)];

    //NSString* questionString = [questionModel.questionTitle substringWithRange:<#(NSRange)#>]
    for(int i = 0; i < questionModel.questionTitle.length/*questionStr.length*/; i++){
        NSString *pinyinString = [questionModel.questionTitle/*questionStr*/ substringWithRange:NSMakeRange(i, 1)];
        NSArray* pinyinArray = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",
                                 @"15",@"16",@"17",@"18",@"19",@".",@",",@"?",@"，",@"。",@"？",@"(",@")",@"（",@"）",@" "];

        if(/*[pinyinString containsString:@"？"]
           || [pinyinString containsString:@"，"]
           || [pinyinString containsString:@"。"]*/[pinyinArray containsObject:pinyinString]){
            UIView* pinyin = [_pinyinView viewWithTag:(300+i)];//viewArrya[questionIndex];
            NSArray* pinyinViews = [pinyin subviews];
            UILabel* pinyin1 =pinyinViews[0];
            [pinyin1 setTextColor:[UIColor greenColor]];
            UILabel* pinyin2 =pinyinViews[1];
            [pinyin2 setTextColor:[UIColor greenColor]];
            v_correct_count++;
            continue;
        }
        if(j >= questionModel.questionUserAnswer.length){
            return;
        }
        NSString *answerString = [questionModel.questionUserAnswer substringWithRange:NSMakeRange(j, 1)];
        if([pinyinString isEqualToString:answerString]){
            UIView* pinyin = [_pinyinView viewWithTag:(300+i)];//viewArrya[questionIndex];
            NSArray* pinyinViews = [pinyin subviews];
            UILabel* pinyin1 =pinyinViews[0];
            [pinyin1 setTextColor:[UIColor greenColor]];
            UILabel* pinyin2 =pinyinViews[1];
            [pinyin2 setTextColor:[UIColor greenColor]];
            v_correct_count++;
        }else{
            UIView* pinyin = [_pinyinView viewWithTag:(300+i)];//viewArrya[questionIndex];
            NSArray* pinyinViews = [pinyin subviews];
            UILabel* pinyin1 =pinyinViews[0];
            [pinyin1 setTextColor:[UIColor redColor]];
            UILabel* pinyin2 =pinyinViews[1];
            [pinyin2 setTextColor:[UIColor redColor]];

        }
        j++;
    }
    
    if(true == addPoint && v_correct_count == questionModel.questionTitle.length){
        questionModel.questionValue =5;
        [self updateRightItem];
    }
    
    
}

- (void)onError:(int)errorCode{
    NSLog(@"zlwu errorCode");

}

-(void)setDetailClassM:(JrdNodeModel *)jzClassM{
    self.courseModel = jzClassM;
}


-(void)initToParseXML{
    NSString* doc = [NSString stringWithFormat:@"http://120.55.86.220/%@",_courseModel.NodeDocUrl];
    NSString* doc_name = [doc stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL* url = [NSURL URLWithString:doc_name];
    // load web doc
    NSData *data1 = [[NSData alloc] initWithContentsOfURL:url];
    [self XMLParserWithData:data1];
}

-(void)XMLParserWithData:(NSData *)data{
    

    //1.创建NSXMLParser
    NSXMLParser *XMLParser = [[NSXMLParser alloc] initWithData:data];
    //2.设置代理
    [XMLParser setDelegate:self];
    //3.开始解析
    [XMLParser parse];
}


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    NSLog(@"zlwu add for elementName = %@", elementName);
    xmlElements=[[NSString alloc]initWithString:elementName];
}

- (void)parser:(NSXMLParser *)parser foundComment:(NSString *)comment{
    NSLog(@"zlwu add for elementName =");
}

- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock{
    NSLog(@"zlwu add for elementName =");

}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    NSLog(@"zlwu string = %@",string);
    if([xmlElements isEqualToString:@"READING"]){
        //start to build readQuestionArray
        v_is_choice = false;
    }else if([xmlElements isEqualToString:@"CHOICE"]){
        //start to build choiceQuestionArray
        v_is_choice = true;
    }

    if(false == v_is_choice){
        NSLog(@"zlwu add for reding: string = %@", string);
        if(![string containsString:@"\n"] && [xmlElements isEqualToString:@"TITLE"]){
            if(nil == preString){
                preString = string;
            }else{
                preString = [NSString stringWithFormat:@"%@%@", preString, string];
            }
        }else{
            if(nil != preString){
                choiceModel = [[JrdQuestionModelExt alloc] init];
                choiceModel.questionType  = QUESTION_TYPE_READING;
                choiceModel.questionTitle = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                preString = nil;
                [questionArray addObject:choiceModel];
            }
        }
    }else{
        
        if([xmlElements isEqualToString:@"ITEM"]){
           choiceModel  = [[JrdQuestionModelExt alloc] init];
        }
        /*if([xmlElements isEqualToString:@"TITLE"] && ![string containsString:@"\n"]){
            if(nil == preString){
                preString = string;
            }else{
                preString = [NSString stringWithFormat:@"%@%@", preString, string];
            }
        }else{
            if(nil != preString){
                choiceModel.questionTitle = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                preString = nil;
            }
        }*/
        if([xmlElements isEqualToString:@"TITLE"]){
            if(![string containsString:@"\n"]){
                if(nil == preString){
                    preString = string;
                }else{
                    preString = [NSString stringWithFormat:@"%@%@", preString, string];
                }
            }else{
                if(nil != preString && ![preString containsString:@"\n"]){
                    choiceModel.questionTitle = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                    preString = nil;
                }
            }
        }
        
        
        /*if([xmlElements isEqualToString:@"CHOICEA"]&& ![string containsString:@"\n"]){
            if(nil == preString){
                preString = string;
            }else{
                preString = [NSString stringWithFormat:@"%@%@", preString, string];
            }
        }else{
            if(nil != preString){
                choiceModel.questionChoice1 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                preString = nil;
            }
        }*/
        if([xmlElements isEqualToString:@"CHOICEA"]){
            if(![string containsString:@"\n"]){
                if(nil == preString){
                    preString = string;
                }else{
                    preString = [NSString stringWithFormat:@"%@%@", preString, string];
                }
            }else{
                if(nil != preString && ![preString containsString:@"\n"]){
                    choiceModel.questionChoice1 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                    preString = nil;
                }
            }

        }
        

        /*if([xmlElements isEqualToString:@"CHOICEB"]&& ![string containsString:@"\n"]){
            if(nil == preString){
                preString = string;
            }else{
                preString = [NSString stringWithFormat:@"%@%@", preString, string];
            }
        }else{
            if(nil != preString){
                choiceModel.questionChoice2 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                preString = nil;
            }
        }*/

        
        if([xmlElements isEqualToString:@"CHOICEB"]){
            if(![string containsString:@"\n"]){
                if(nil == preString){
                    preString = string;
                }else{
                    preString = [NSString stringWithFormat:@"%@%@", preString, string];
                }
            }else{
                if(nil != preString && ![preString containsString:@"\n"]){
                    choiceModel.questionChoice2 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                    preString = nil;
                }
            }
            
        }

        /*if([xmlElements isEqualToString:@"CHOICEC"]&& ![string containsString:@"\n"]){
            if(nil == preString){
                preString = string;
            }else{
                preString = [NSString stringWithFormat:@"%@%@", preString, string];
            }
        }else{
            if(nil != preString){
                choiceModel.questionChoice3 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                preString = nil;
            }
        }*/
        if([xmlElements isEqualToString:@"CHOICEC"]){
            if(![string containsString:@"\n"]){
                if(nil == preString){
                    preString = string;
                }else{
                    preString = [NSString stringWithFormat:@"%@%@", preString, string];
                }
            }else{
                if(nil != preString && ![preString containsString:@"\n"]){
                    choiceModel.questionChoice3 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                    preString = nil;
                }
            }
            
        }


        /*if([xmlElements isEqualToString:@"CHOICED"]&& ![string containsString:@"\n"]){
            if(nil == preString){
                preString = string;
            }else{
                preString = [NSString stringWithFormat:@"%@%@", preString, string];
            }
        }else{
            if(nil != preString){
                choiceModel.questionChoice4 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                preString = nil;
            }
        }*/
        if([xmlElements isEqualToString:@"CHOICED"]){
            if(![string containsString:@"\n"]){
                if(nil == preString){
                    preString = string;
                }else{
                    preString = [NSString stringWithFormat:@"%@%@", preString, string];
                }
            }else{
                if(nil != preString && ![preString containsString:@"\n"]){
                    choiceModel.questionChoice4 = preString;//[NSString stringWithFormat:@"%@%@", preString, string];
                    preString = nil;
                }
            }
            
        }


        if([xmlElements isEqualToString:@"ANSWER"]){
            if(![string containsString:@"\n"]){
                if(nil == preString){
                    preString = string;
                }else{
                    preString = [NSString stringWithFormat:@"%@%@", preString, string];
                }
            }else{
                if(nil != preString && ![preString containsString:@"\n"]){
                    choiceModel.questionAnswer = preString;
                    choiceModel.questionType  = QUESTION_TYPE_CHOICE;
                    [questionArray addObject:choiceModel];
                    preString = nil;
                }
            }
            
        }

        /*if([xmlElements isEqualToString:@"ANSWER"]&& ![string containsString:@"\n"]){
            if(nil == preString){
                preString = string;
            }else{
                preString = [NSString stringWithFormat:@"%@%@", preString, string];
            }
        }else{
            if(nil != preString){
                choiceModel.questionAnswer = string;
                choiceModel.questionType  = QUESTION_TYPE_CHOICE;
                [questionArray addObject:choiceModel];
                preString = nil;
            }
        }*/
    }
    
    NSLog(@"finish");
}



-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    NSLog(@"zlwu add for didEndElement, elementName = %@", elementName);
    //go to get user answer
    if([elementName isEqualToString:@"QUESTION"]){
        NSString * searchCondition = [NSString stringWithFormat:@"question_node_id=%@ and user_id=%@",
                                      _courseModel.NodeID, [JrdDatamanager manager].user.userId];

        NSArray* nodeListData= [manager searchDataFromSheet:@"question_list" where:searchCondition];

        //[self configureQuestionView];
        if(0 != nodeListData.count){
            for(int i = 0 ; i < nodeListData.count; i++){
                JrdQuestionModelExt* questionModel = [questionArray objectAtIndex:i];
                questionModel.questionUserAnswer = nodeListData[i][QUESTION_USER_ANSWER];
                questionModel.questionValue =[nodeListData[i][QUESTION_VALUE] intValue];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self configureQuestionView];
            [self updateRightItem];
        });
    }
}


@end
